package com.hyt.it.ogt.controller.ykcj.grade;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.hyt.common.apiInfor.DataType;
import com.hyt.common.apiInfor.ParamType;
import com.hyt.exception.exception.BusinessLogicException;
import com.hyt.it.ogt.common.config.ApiVersionConstant;
import com.hyt.it.ogt.controller.base.BaseController;
import com.hyt.it.ogt.ykcj.common.annotation.Log;
import com.hyt.it.ogt.ykcj.common.core.domain.AjaxResult;
import com.hyt.it.ogt.ykcj.common.core.page.TableDataInfo;
import com.hyt.it.ogt.ykcj.common.enums.BusinessType;
import com.hyt.it.ogt.ykcj.common.enums.CommonEnums;
import com.hyt.it.ogt.ykcj.common.enums.ExamResultDownLoadFileTypeEnum;
import com.hyt.it.ogt.ykcj.common.enums.FileType;
import com.hyt.it.ogt.ykcj.common.exception.CustomException;
import com.hyt.it.ogt.ykcj.domain.vo.AddEnterpriseExamineeInfoVo;
import com.hyt.it.ogt.ykcj.domain.vo.CandidateInfoVo;
import com.hyt.it.ogt.ykcj.domain.vo.EnterpriseExamineeInfoVo;
import com.hyt.it.ogt.ykcj.domain.vo.QueryEnterpriseExamineeGradeVo;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeGradeExportService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeGradeImportService;
import com.hyt.it.ogt.ykcj.service.grade.IEnterpriseExamineeInfoService;
import com.hyt.it.ogt.ykcj.service.zs.IZsInfoService;
import com.hyt.loginfo.model.User;
import com.hyt.loginfo.service.IBaseLoginService;
import com.hyt.progress.creator.anno.ProgressAnno;
import com.hyt.swagger.ApiVersion;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 企业招聘考生成绩信息Controller
 *
 * @author liying
 * @date 2021-11-19
 */
@Api(tags = "grade.9.企业招聘考生成绩信息")
@ApiSort(value = 209)
@RestController
@RequestMapping("/enterprise/grade/info")
@Slf4j
public class EnterpriseExamineeInfoController extends BaseController {

    @Autowired
    private IEnterpriseExamineeInfoService enterpriseExamineeInfoService;

    @Autowired
    private IEnterpriseExamineeGradeImportService enterpriseExamineeGradeImportService;

    @Autowired
    private IBaseLoginService baseLoginService;

    @Autowired
    private IEnterpriseExamineeGradeExportService enterpriseExamineeGradeExportService;

    @Autowired
    private IZsInfoService zsInfoService;


    /**
     * 查询企业招聘考生信息列表
     */
    @ApiOperation(value = "查询企业招聘考生信息列表", response = EnterpriseExamineeInfoVo.class)
    @ApiVersion(group = {ApiVersionConstant.V2_4_9, ApiVersionConstant.V2_4_10})
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) {
        PageInfo<List<EnterpriseExamineeInfoVo>> pageInfo = enterpriseExamineeInfoService.selectEnterpriseExamineeGradePage(queryExamineeGradeVo);
        return getDataTable(pageInfo);
    }

    /**
     * 导出考试总成绩导入模板文件
     *
     * @param examId 考试名称
     */
    @GetMapping("getExamTpl/{examId}")
    @ApiOperation(value = "1.1根据examId导出总成绩导入模板 ", notes = "（传examId（必传））没有对应文件响应为空")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true)
    })
    @ApiOperationSort(1)
    public void getExamTpl(@PathVariable(name = "examId", required = true) String examId,
                           HttpServletResponse response, HttpServletRequest request) {

        XSSFWorkbook wb = enterpriseExamineeGradeExportService.getExamTpl(examId, null);
        OutputStream fos = null;
        try {
            response.setContentType("octets/stream");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(CommonEnums.EXPORT_IMPORT_TOTAL_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            fos = response.getOutputStream();
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败：{}", e);
        } finally {
            try {
                if (null != wb) {
                    wb.close();
                }
                if (null != fos) {
                    fos.close();
                }

            } catch (IOException e) {
                logger.error("关闭文件下载流失败：{}", e);
            }
        }
    }

    /**
     * 导出考试科目成绩导入模板文件
     *
     * @param examId 考试名称
     */
    @GetMapping("getExamSubjectTpl/{examId}/{subject}")
    @ApiOperation(value = "1.2根据examId,subject导出科目导入模板 ", notes = "（传examId（必传），subject(必传)）没有对应文件响应为空")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true),
            @ApiImplicitParam(name = "subject", value = "科目id", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true)
    })
    @ApiOperationSort(2)
    public void getExamSubjectTpl(@PathVariable(name = "examId", required = true) String examId,
                                  @PathVariable(name = "subject", required = true) String subject,
                                  HttpServletResponse response, HttpServletRequest request) {

        XSSFWorkbook wb = enterpriseExamineeGradeExportService.getExamTpl(examId, subject);
        OutputStream fos = null;
        try {
            response.setContentType("octets/stream");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(CommonEnums.EXPORT_IMPORT_SUBJECT_FILE_NAME.getDesc().getBytes("gb2312"), "ISO8859-1") + ".xlsx");
            fos = response.getOutputStream();
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error("下载文件失败：{}", e);
        } finally {
            try {
                if (null != wb) {
                    wb.close();
                }
                if (null != fos) {
                    fos.close();
                }

            } catch (IOException e) {
                logger.error("关闭文件下载流失败：{}", e);
            }
        }
    }

    /**
     * 导出未归档企业招聘考生考试总成绩信息列表
     */
    @Log(title = "导出未归档企业招聘考生考试总成绩信息", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "2.1导出未归档企业招聘考生考试总成绩信息列表", notes = "(参数为：examineeIds（非必须传），examId（必传）)" +
            "导出接口是获取文件名称，通过返回的文件名称再进行文件的导出,调用接口：/common/download，delete参数传true删除下载,  "
            + "200：成功；52292101：查询不到当前用户信息,52292102: 考试id不能为空,52292103: 文件正在下载中请耐心等待,52292104:下载的内容为空，下载失败")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examineeIds", value = "考生ids,不传则导出该考试下的所有学生", dataType = DataType.ARRAY,
                    paramType = ParamType.QUERY, required = false),
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(3)
    @ApiVersion(group = {ApiVersionConstant.V2_4_10})
    @ProgressAnno(errorCode = 52292105, timeoutSeconds = 60 * 10)
    @GetMapping("/export")
    public void export(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) throws Exception {
        logger.info("# 导出未归档企业招聘考生考试总成绩信息参数 ： {}", JSON.toJSON(queryEnterpriseExamineeGradeVo));
        User user = baseLoginService.getSysUser();
        if (null == user) {
            BusinessLogicException.throwException(52292101, "查询不到当前用户信息");
        }
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52292102, "考试id不能为空");
        }

        queryEnterpriseExamineeGradeVo.setDeptIds(baseLoginService.getDeptIds());
        queryEnterpriseExamineeGradeVo.setArchivedStatus("N");
        //方法里面有重新设置名称的，这里只是为了防止为空的设置，没太多意义
        queryEnterpriseExamineeGradeVo.setFileName(CommonEnums.EXPORT_FILE_NAME.getDesc());
        queryEnterpriseExamineeGradeVo.setSheetName(CommonEnums.EXPORT_SHEET_NAME.getDesc());
        enterpriseExamineeGradeExportService.exportExcelByCondition(queryEnterpriseExamineeGradeVo, user, ExamResultDownLoadFileTypeEnum.ENTERPRISEUNARCHIVED);
    }

    /**
     * 导出归档的企业招聘考生考试总成绩信息列表
     */
    @Log(title = "导出归档的企业招聘考生考试总成绩信息", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "2.2导出归档的企业招聘考生考试总成绩信息列表", notes = "(参数为：examineeIds（非必须传），examId（必传）)" +
            "导出接口是获取文件名称，通过返回的文件名称再进行文件的导出，调用接口：/common/download，delete参数传true删除下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examineeIds", value = "考生ids,不传则导出该考试下的所有学生", dataType = DataType.ARRAY,
                    paramType = ParamType.QUERY, required = false),
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(4)
    @ApiVersion(group = {ApiVersionConstant.V2_4_10})
    @ProgressAnno(errorCode = 52292201, timeoutSeconds = 60 * 10)
    @GetMapping("/exportArchived")
    public void exportArchived(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) throws Exception {
        logger.info("导出文件：" + System.currentTimeMillis());
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52292202, "请选择一个考试");
        }
        User user = baseLoginService.getSysUser();
        queryEnterpriseExamineeGradeVo.setDeptIds(baseLoginService.getDeptIds());
        queryEnterpriseExamineeGradeVo.setArchivedStatus("Y");
        queryEnterpriseExamineeGradeVo.setFileName(CommonEnums.EXPORT_FILE_NAME.getDesc());
        queryEnterpriseExamineeGradeVo.setSheetName(CommonEnums.EXPORT_SHEET_NAME.getDesc());
        enterpriseExamineeGradeExportService.exportExcelByCondition(queryEnterpriseExamineeGradeVo, user, ExamResultDownLoadFileTypeEnum.ENTERPRISEARCHIVED);
    }

    /**
     * 导出未归档企业招聘考生考试单科成绩信息列表
     */
    @Log(title = "导出未归档企业招聘考生考试单科成绩信息", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "3.1导出未归档企业招聘考生考试单科成绩信息列表", notes = "(参数为：examineeIds（非必须传），examId（必传），subjectId（必传）)" +
            "导出接口是获取文件名称，通过返回的文件名称再进行文件的导出,调用接口：/common/download，delete参数传true删除下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examineeIds", value = "考生ids,不传则导出该考试下的所有学生", dataType = DataType.ARRAY,
                    paramType = ParamType.QUERY, required = false),
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "subjectId", value = "选择的科目", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(5)
    @ApiVersion(group = {ApiVersionConstant.V2_4_10})
    @ProgressAnno(errorCode = 52293101, timeoutSeconds = 60 * 10)
    @GetMapping("/exportSubject")
    public void exportSubject(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) throws Exception {
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52293102, "请选择一个考试");
        }
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getSubjectId())) {
            BusinessLogicException.throwException(52293103, "请选择一个科目");
        }
        User user = baseLoginService.getSysUser();
        if (null == user) {
            BusinessLogicException.throwException(52292101, "查询不到当前用户信息");
        }
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52292102, "考试id不能为空");
        }
        queryEnterpriseExamineeGradeVo.setDeptIds(baseLoginService.getDeptIds());
        queryEnterpriseExamineeGradeVo.setArchivedStatus("N");
        //方法里面有重新设置名称的，这里只是为了防止为空的设置，没太多意义
        queryEnterpriseExamineeGradeVo.setFileName(CommonEnums.EXPORT_SUBJECT_FILE_NAME.getDesc());
        queryEnterpriseExamineeGradeVo.setSheetName(CommonEnums.EXPORT_SUBJECT_SHEET_NAME.getDesc());
        enterpriseExamineeGradeExportService.exportSubjectExcelByCondition(queryEnterpriseExamineeGradeVo, user, ExamResultDownLoadFileTypeEnum.ENTERPRISEUNARCHIVED);
    }

    /**
     * 导出未归档企业招聘考生考试单科成绩信息列表
     */
    @Log(title = "导出归档企业招聘考生考试单科成绩信息", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "3.2导出归档企业招聘考生考试单科成绩信息列表", notes = "(参数为：examineeIds（非必须传），examId（必传），subjectId（必传）)" +
            "导出接口是获取文件名称，通过返回的文件名称再进行文件的导出,调用接口：/common/download，delete参数传true删除下载")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examineeIds", value = "考生ids,不传则导出该考试下的所有学生", dataType = DataType.ARRAY,
                    paramType = ParamType.QUERY, required = false),
            @ApiImplicitParam(name = "examId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true),
            @ApiImplicitParam(name = "subjectId", value = "选择得科目", dataType = DataType.STRING,
                    paramType = ParamType.QUERY, required = true)
    })
    @ApiOperationSort(6)
    @ApiVersion(group = {ApiVersionConstant.V2_4_10})
    @ProgressAnno(errorCode = 52293201, timeoutSeconds = 60 * 10)
    @GetMapping("/exportSubjectArchived")
    public void exportSubjectArchived(QueryEnterpriseExamineeGradeVo queryEnterpriseExamineeGradeVo) throws Exception {
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52293102, "请选择一个考试");
        }
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getSubjectId())) {
            BusinessLogicException.throwException(52293103, "请选择一个科目");
        }
        User user = baseLoginService.getSysUser();
        if (null == user) {
            BusinessLogicException.throwException(52292101, "查询不到当前用户信息");
        }
        if (StringUtils.isEmpty(queryEnterpriseExamineeGradeVo.getExamId())) {
            BusinessLogicException.throwException(52292102, "考试id不能为空");
        }
        queryEnterpriseExamineeGradeVo.setDeptIds(baseLoginService.getDeptIds());
        queryEnterpriseExamineeGradeVo.setArchivedStatus("Y");
        queryEnterpriseExamineeGradeVo.setFileName(CommonEnums.EXPORT_SUBJECT_FILE_NAME.getDesc());
        queryEnterpriseExamineeGradeVo.setSheetName(CommonEnums.EXPORT_SUBJECT_SHEET_NAME.getDesc());
        enterpriseExamineeGradeExportService.exportSubjectExcelByCondition(queryEnterpriseExamineeGradeVo, user, ExamResultDownLoadFileTypeEnum.ENTERPRISEARCHIVED);
    }

    /**
     * 获取企业招聘考生信息详细信息
     */
    @ApiOperation(value = "4.1获取企业招聘考生详细信息", notes = "(参数为：fileType为字段类型字段：'1'：直接展示的文本，“2”：图片地址，'3':不用展示)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "examinId", value = "考试id", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true),
            @ApiImplicitParam(name = "examineeId", value = "考生id", dataType = DataType.STRING,
                    paramType = ParamType.PATH, required = true)
    })
    @ApiOperationSort(7)
    @GetMapping(value = "/{examinId}/{examineeId}")
    public AjaxResult getExamineeInfo(@PathVariable(value = "examinId", required = true) String examinId,
                                      @PathVariable(value = "examineeId", required = true) String examineeId) {
        if (StringUtils.isEmpty(examinId)) {
            return AjaxResult.success("请填写正确的考生id");
        }
        if (StringUtils.isEmpty(examineeId)) {
            return AjaxResult.error("请填写正确的考试id");
        }
        List<CandidateInfoVo> candidateInfoVoList = enterpriseExamineeInfoService.getExamineeInfo(examinId, examineeId);
        return AjaxResult.success(candidateInfoVoList);
    }

    /**
     * 获取企业招聘考生信息详细信息
     */
    @ApiOperation("获取企业招聘考生成绩信息详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(enterpriseExamineeInfoService.selectEnterpriseExamineeGradeById(id));
    }


    /**
     * 保存企业招聘生成绩信息
     */
    @ApiOperation("保存企业招聘考生成绩信息")
    @Log(title = "企业招聘考生信息", businessType = BusinessType.INSERT)
    @PostMapping("/saveEnterpriseExamineeGrade")
    public AjaxResult saveEnterpriseExamineeGrade(@RequestBody AddEnterpriseExamineeInfoVo enterpriseExamineeInfoVo) throws Exception {
        return AjaxResult.success(enterpriseExamineeInfoService.saveEnterpriseExamineeGrade(enterpriseExamineeInfoVo));
    }

    /**
     * 删除企业招聘考生成绩信息
     */
    @ApiOperation("删除企业招聘考生成绩信息")
    @Log(title = "企业招聘考生信息", businessType = BusinessType.DELETE)
    @PostMapping("/deleteEnterpriseExaminee")
    public AjaxResult remove(@RequestBody QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {
        return toAjax(enterpriseExamineeInfoService.deleteEnterpriseExamineeGrade(queryExamineeGradeVo));
    }


    @ApiOperation("成绩归档")
    @Log(title = "成绩归档", businessType = BusinessType.UPDATE)
    @PostMapping("/archive")
    public AjaxResult archive(@RequestBody QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {
        // 成绩归档的时候检查是否关联证书已经发布
        if (StringUtils.isEmpty(queryExamineeGradeVo.getExamId())) {
            throw new CustomException("考试ID不能为空！");
        }
        if (null == queryExamineeGradeVo.getExamineeIds() || queryExamineeGradeVo.getExamineeIds().length < 1) {
            throw new CustomException("考生ID不能为空！");
        }
        return toAjax(enterpriseExamineeInfoService.updateEnterpriseExamineeArchive(queryExamineeGradeVo));
    }


    @ApiOperation("取消归档")
    @Log(title = "取消归档", businessType = BusinessType.UPDATE)
    @PostMapping("/cancelArchive")
    public AjaxResult cancelArchive(@RequestBody QueryEnterpriseExamineeGradeVo queryExamineeGradeVo) throws Exception {
        return toAjax(enterpriseExamineeInfoService.cancelEnterpriseExamineeArchive(queryExamineeGradeVo));
    }


    @ApiOperation("导入成绩(企业招聘)")
    @Log(title = "导入成绩", businessType = BusinessType.IMPORT)
    @PostMapping("/importEnterpriseGradeInfo")
    public AjaxResult importGradeInfo(MultipartFile file, String examId, String subjectId) throws Exception {
        if (null == file) {
            return AjaxResult.error("文件为空！");
        }
        enterpriseExamineeInfoService.checkExamineeOrigin(examId);
        // 校验文件格式
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            return AjaxResult.error("文件名称为空！");
        }
        String fileType = fileName.substring(fileName.indexOf("."));
        Object[] objects;
        if (FileType.FILE_TYPE_XLSX.getType().equals(fileType) || FileType.FILE_TYPE_XLS.getType().equals(fileType)) {
            objects = enterpriseExamineeGradeImportService.importtExcelFile(file, examId, subjectId);
        } else {
            return AjaxResult.error("文件类型错误！");
        }
        return new Boolean(objects[0].toString()) ? AjaxResult.success("导入成功", objects[1]) : AjaxResult.error("导入失败", objects[1]);
    }

    /**
     * 测试接口
     *
     * @param examId
     * @return
     */
    @ApiOperation("测试接口")
    @Log(title = "测试接口", businessType = BusinessType.UPDATE)
    @GetMapping("/refreshExamineeQualified/{examId}")
    public AjaxResult refreshExamineeQualified(@PathVariable String examId) {

        enterpriseExamineeInfoService.refreshEnterpriseExamineeQualified(examId);
        return AjaxResult.success(1);
    }

}
